package com.imchen;


import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

public class Main {

    private static String url = "https://api.clickzain.xyz/api/sdk/hot-patch";
    static String key = "245031832";

    public static void main(String[] args) {
        // write your code here
//        aa86daf9d34c6e4433a01f3c4b87232c  原版
//        67edd098a005457c2ee14b0f04320fd4
//        aa86daf9d34c6e4433a01f3c4b87232c
//        67edd098a005457c2ee14b0f04320fd4  加密
//        decy("//home//imch1n//Developer//workSpaces//sdk-android//release-out//placo_dex.jar");
//        String md5=getFileMD5(new File("//home//imch1n//Developer//workSpaces//sdk-android//release-out//placo_dex.jar"));
//        System.out.println("md5:"+md5);
//        String result = encString("使用公钥加密，私钥解密dPatch.jar");
//        System.out.println("Encrypt:"+result);
//        String decryptStr=decString(result,key);
//        System.out.printf("decrypt result:%s \n",decryptStr);
//        String url=new String(new byte[]{ 104, 116, 116, 112, 115, 58, 47, 47, 97, 112, 105, 46, 99, 108, 105, 99, 107, 122, 97, 105, 110, 46, 120, 121, 122, 47, 97, 112, 105, 47, 115, 100, 107, 47, 104, 111, 116, 45, 112, 97, 116, 99, 104});
//        System.out.println(url);
//        saxXml("/home/imch1n/AndroidManifest.xml");
//        renameDir("/home/imch1n/Developer/AutoPackage/oxygen/oxygen_01010101010/","/home/imch1n/Developer/AutoPackage/oxygen/oxygen_01010101010/");
//        renameDir("/home/imch1n/Developer/AutoPackage/oxygen/oxygen_01010101010/oxygen","/home/imch1n/Developer/AutoPackage/oxygen/oxygen_01010101010/oxygenpp");
//        randomFile("/home/imch1n/Developer/Test/oxygen/src/main/java/com/imchw/oxygen/OxygenBiu.java");
//        randomFile("/home/imch1n/Developer/Scripts/EncryptTools/src/com/imchen/test.txt");
//        String result = fileToArray("/home/imch1n/Music/静音.mp3");
//        stringToFile(result, "/home/imch1n/Music/test.mp3");
//        stringToByte("http://static.clickclaro.com/storage/hot-patches/1.3.11.placo_dex.jar");
        //插件的加密和加密
        decy("/home/imch1n/Developer/workSpaces/sdk-android/release-out/patch.jar");
        System.out.println("md5:"+getFileMD5(new File("/home/imch1n/Developer/workSpaces/sdk-android/release-out/patch.jar")));
//        System.out.println(new String(new byte[]{100, 80, 97, 116, 99, 104, 46, 106, 97, 114}));

    }

    /**
     * 反向加密dex文件
     *
     * @param p
     */
    public static void decy(String p) {
        byte b[] = new byte[2048];
        try {

            RandomAccessFile r = new RandomAccessFile(p, "rw");
            r.read(b);
            for (int i = 0; i < b.length; i++)
                b[i] = (byte) (~b[i]);
            r.seek(0);
            r.write(b);
            r.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取文件的MD5
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        MessageDigest MD5 = null;
        FileInputStream fis = null;
        int length = 0;
        byte[] buffer = new byte[1024];
        try {
            if (file.exists() && file.isFile()) {
                MD5 = MessageDigest.getInstance("MD5");
                fis = new FileInputStream(file);
                while ((length = fis.read(buffer, 0, 1024)) != -1) {
                    MD5.update(buffer, 0, length);
                }
                BigInteger bigInteger = new BigInteger(1, MD5.digest());
                return bigInteger.toString(16);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptByName(String content) {

        return null;
    }


    /**
     * 字符串加密算法
     *
     * @param content 需要加密的字符串
     * @return
     */
    public static String encString(String content) {

        SimpleDateFormat sdf = new SimpleDateFormat("ddMhhmmss");
        String time = sdf.format(new Date(System.currentTimeMillis()));

        int num = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            if (i % 2 == 0) {
                num = ~content.charAt(i);
            } else {
                num = content.charAt(i) + Integer.parseInt(key);
            }
            sb.append((char) num);
        }
        return sb.toString();
    }

    /**
     * 解密字符串
     *
     * @param encString
     * @param password
     * @return
     */
    public static String decString(String encString, String password) {
        int num = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < encString.length(); i++) {
            if (i % 2 == 0) {
                num = ~encString.charAt(i);
            } else {
                num = (encString.charAt(i) - Integer.parseInt(password));
            }
            sb.append((char) num);
        }
        return sb.toString();
    }

    /**
     * 解析xml
     *
     * @param path
     */
    public static void saxXml(String path) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new File(path));
            Element element = document.getDocumentElement();
            System.out.printf("element tag name:%s\n", element.getTagName());
            NodeList nodeList = element.getElementsByTagName("receiver");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NamedNodeMap namedNodeMap = node.getAttributes();
                for (int j = 0; j < namedNodeMap.getLength(); j++) {
                    Node childNode = namedNodeMap.item(j);
                    System.out.printf("node name:%s node value:%s\n", childNode.getNodeName(), childNode.getNodeValue());

                    childNode.setNodeValue("com.imchen.aaabbb");
                    System.out.printf("node name:%s node value:%s\n", childNode.getNodeName(), childNode.getNodeValue());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重命名文件
     *
     * @param originalDir
     * @param newDir
     */
    public static void renameDir(String originalDir, String newDir) {
        File file = new File(originalDir);
        boolean isRename = file.renameTo(new File(newDir));
        System.out.printf("rename status:%s\n", isRename);
    }


    public static void randomFile(String path) {
        File file = new File(path);
        String line = null;
        long point = 0;
        long currentPoint;
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            while ((line = randomAccessFile.readLine()) != null) {
                currentPoint = randomAccessFile.getFilePointer();
                System.out.printf("pointer:%s  currentPointer:%s\n", point, randomAccessFile.getFilePointer());
                line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
                System.out.printf("%s\n", line);


                if (line.contains("com.imchw.oxygen")) {
                    randomAccessFile.seek(point);
                    randomAccessFile.write("A".getBytes());

//                    line=line.replace("com.imchw.oxygen","com.imchw.oxygenCHENFFFFF");
//                    if (line.startsWith("package")||line.startsWith("import")){
//                        line+="\n";
//                    }
//                    randomAccessFile.write(line.getBytes("UTF-8"));
                }


            }
//            randomAccessFile.seek(26);
//            randomAccessFile.writeUTF("rqrwr4111111111");
//            System.out.println(randomAccessFile.readLine());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void fileToArray(Context context,byte[] audioByte){
//        try {
//            File tmpFile=File.createTempFile("uu","m4r",context.getCacheDir());
//            FileOutputStream tmpFos=new FileOutputStream(tmpFile);
//            tmpFos.write(audioByte);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public static String fileToArray(String path) {
        File file = new File(path);
        FileInputStream fis;
        byte[] bytes = new byte[2048];
        String result = null;
        List<byte[]> listByte = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        try {
            fis = new FileInputStream(file);
            while ((fis.read(bytes)) != -1) {
                result = new String(Base64.getEncoder().encode(bytes));
                builder.append(result);
                builder.append(",");
//                System.out.println("result:"+result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        result = builder.toString();
        System.out.println(result);
        return result;
    }

    public static void stringToFile(String content, String path) {
        String[] base64Str = content.split(",");
        String tmpStr = null;
        int size = base64Str.length;
        System.out.println("size:" + size);
        byte[] tmpByte = null;
        byte[] buffer = new byte[2048];

        try {
            FileOutputStream fos = new FileOutputStream(path);
            for (int i = 0; i < size; i++) {
                tmpStr = base64Str[i];
                if (i == size - 2) {
                    tmpStr.replace(",", "");
                }
                tmpByte = Base64.getDecoder().decode(tmpStr.getBytes());
                fos.write(tmpByte);
            }
            System.out.println("write file finish! locate at:" + path);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void stringToByte(String content) {
        StringBuilder builder = new StringBuilder();
        int toInt;
        for (int i = 0; i < content.length(); i++) {
            toInt = (int) content.charAt(i);
            builder.append(toInt);
            if (i < content.length() - 1) {
                builder.append(", ");
            }
        }
        System.out.println("result :" + builder.toString());
        System.out.println("newString result:" + new String(new byte[]{104, 116, 116, 112, 58, 47, 47, 115, 116, 97, 116, 105, 99, 46, 99, 108, 105, 99, 107, 99, 108, 97, 114, 111, 46, 99, 111, 109, 47, 115, 116, 111, 114, 97, 103, 101, 47, 104, 111, 116, 45, 112, 97, 116, 99, 104, 101, 115, 47, 49, 46, 51, 46, 49, 49, 46, 112, 108, 97, 99, 111, 95, 100, 101, 120, 46, 106, 97, 114}));
        System.out.println("newString result:" + new String(new byte[]{104, 116, 116, 112, 115, 58, 47, 47, 97, 112, 105, 46, 99, 108, 105, 99, 107, 122, 97, 105, 110, 46, 120, 121, 122, 47, 97, 112, 105, 47, 115, 100, 107, 47, 104, 111, 116, 45, 112, 97, 116, 99, 104}));
    }

}
